#include "worker.h"
#include "head.h"
#include "download.h"

void unlock(void *parg){
    pthread_mutex_t *pMutex = (pthread_mutex_t *)parg;
    pthread_mutex_unlock(pMutex);
}

int makeWorker(threadPool_t* pThreadPool){
    for(int i = 0; i < pThreadPool->threadNum; i++){
        pthread_create(pThreadPool->tidArr + i, NULL, threadFunc, (void *)pThreadPool);
    }
}

void *threadFunc(void *parg){
    threadPool_t* pThreadPool = (threadPool_t *)parg;
    while(1){
        int netFd;
        pthread_mutex_lock(&pThreadPool->mutex);
        pthread_cleanup_push(unlock, &pThreadPool->mutex);
        while(pThreadPool->taskQueue.size == 0 && pThreadPool->isThreadPoolRunning == 1){
            pthread_cond_wait(&pThreadPool->cond, &pThreadPool->mutex);
        }
        if(pThreadPool->isThreadPoolRunning == 0){
            puts("Time to die");
            pthread_exit(NULL);
        }
        puts("A worker gets a task");
        netFd = pThreadPool->taskQueue.pFront->netFd;
        deQueue(&pThreadPool->taskQueue);
        pthread_cleanup_pop(1);
        handleEvent(netFd);
        printf("A worker finished his job, tid = %lu\n", pthread_self());
    }
}

int handleEvent(int netFd){
    //transFile(netFd);
    download("gets file1", "/usr1/", netFd);
    close(netFd);
    return 0;
}